<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use think\exception\ValidateException;

// 配置中心
class Config extends BaseController
{
    public function integral()
    {
        $config = Db::name('integral_config')->find(1);
        View::assign('config',$config);
        return View::fetch();
    }

    //保存积分配置
    public function saveIntegral(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        if ($post['now_use'] <= 0 || $post['ready_use'] <= 0 ) {
            return $this->outputAjax('积分必须大于0！');
        }

        try {
            $data = array(
                'ready_use'       => $post['ready_use'],
                'update_time'   => time(),
            );
            if (Db::table('o_integral_config')->where('id', '=',1)->update($data)) {
                return $this->outputAjax('保存成功！',0);
            }
            return $this->outputAjax('保存失败！');
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    public function engine()
    {
        $inf = Db::name('config')->find(1);

        $time = Db::name('operation_record')->order('id', 'desc')->value('time');
        if (!$time) {
            View::assign('time', '-------');
        } else {
            View::assign('time', date('Y-m-d',$time));
        }
        View::assign('inf', $inf);

        return View::fetch();
    }

    public function saveEngine(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        try {
            $update = array(
                'days' => $post['days'],
                'course_num' => $post['course_num'],
                'update_time' => time(),
            );

            if (!Db::name('config')->where('id', '=', 1)->update($update)) {
                return $this->outputAjax('保存失败');
            }

            return $this->outputAjax('保存成功', 0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

}